package me.pplay.playtalk.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.activity.friends.DiscoverActivity;
import me.pplay.playtalk.activity.friends.FriendsMapActivity;
import me.pplay.playtalk.activity.setting.SettingActivity;
import me.pplay.playtalk.activity.setting.SettingAutoTextActivity;
import me.pplay.playtalk.activity.setting.SettingPrivacyControlActivity;
import me.pplay.playtalk.activity.setting.SettingStoreSettingActivity;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.net.SkyidOperation;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.PhbBackUp;
import me.pplay.playtalk.protocol.TpAuth;
import me.pplay.playtalk.protocol.TpFile;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.PlayTalkUtil;
import me.pplay.playtalk.util.ServiceUtil;
import me.pplay.playtalk.util.UserInfo;
import me.pplay.playtalk.util.fileUtil.FileDir;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PlayTalkActivity extends BaseActivity {

	@Override
	protected void onRestart() {
		currentIndex = 0;
		timerStart();
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if(timer != null){
		   timer.cancel();
		   timer = null;
		}
	}

	// View declare
	private LinearLayout pageControlLayout;
	private Button btn_getChatting;
	private TextView mainIconDes_tv, signIn_tv;
	private ImageView iconPoint_1, iconPoint_2, iconPoint_3, iconPoint_4, iconPoint_5;
	private ImageView mainicon_1, mainicon_2, mainicon_3, mainicon_4, mainicon_5;
	// Data declare
	private int currentIndex = 0;
	private final int totalCount = 5;
	private final int DELAYTIME = 2000;
	private boolean isFirstChange = true;
	private List<ImageView> pagePointViewList;
	private Timer timer;
	private final int CHANGEDATA = 1000;
	private TpAuth tpAuth;
	private ProgressDialog progressDialog;
	public static PlayTalkActivity palyTalkContext;;
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			LogManager.LogShow("PlayTalkActivity", "handleMessage msg.what = " + msg.what);
			switch (msg.what) {
			
			case CHANGEDATA:
				changeIconAndValue();
				changePointImageResource();
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_OK:
				progressDialog.dismiss();
				SkyidOperation.saveSkyid(PlayTalkActivity.this);
				Intent intent = new Intent(PlayTalkActivity.this, HomeActivity.class);
				startActivity(intent);
				PlayTalkActivity.this.finish();
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_ERR: {
				progressDialog.dismiss();
				RspData rspdata = (RspData) msg.obj;
				showToast(rspdata.getString() == null ? "SignIn Unkown err" : rspdata.getString());
			}
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT:
				progressDialog.dismiss();
				showToast("SignIn Time out");
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_WAITING:
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState); 
		Bundle bundle=getIntent().getExtras();
		String from = null ;
		if(bundle!=null)
			from = bundle.getString("from");
		int skyId = SkyidOperation.getSid(this);
		LogManager.LogShow("PlayTalkActivity", "*****handleMessage skyId = " + skyId);
		if(from== null ||!from.equals("settingActivity")){
			if(skyId != -1){ 
				Globals.skyid = skyId;
				Intent intent = new Intent(this, HomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				createDir();
				ServiceUtil.startService(PlayTalkActivity.this);
				this.finish();
				return;
			}
			
//			if(Globals.skyid == -1  && skyId != -1){
//				Globals.skyid = skyId;
//				Globals.isFilpMain	= false;
//				Globals.isMessageLoginOn = false;
//				Intent intent = new Intent(this, MessageActivity.class);
//				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				startActivity(intent);
//				createDir();
//				ServiceUtil.startService(PlayTalkActivity.this);
//				this.finish();
//				return;
//			}
		}
		System.out.println("ddddddddd::::::::::::::::::::::::::::::::::end");
		setContentView(R.layout.layout_palytalk);
		UserInfo.setContext(getApplicationContext());
		findViews();
		initDatas();
		clickEvents();
	}

	/**
	 * Get View by viewId
	 */
	private void findViews() {
		pageControlLayout = (LinearLayout) findViewById(R.id.pageControlLayout);
		iconPoint_1 = (ImageView) findViewById(R.id.iconPoint_1);
		iconPoint_2 = (ImageView) findViewById(R.id.iconPoint_2);
		iconPoint_3 = (ImageView) findViewById(R.id.iconPoint_3);
		iconPoint_4 = (ImageView) findViewById(R.id.iconPoint_4);
		iconPoint_5 = (ImageView) findViewById(R.id.iconPoint_5);
		mainicon_1 = (ImageView) findViewById(R.id.mainicon_1);
		mainicon_2 = (ImageView) findViewById(R.id.mainicon_2);
		mainicon_3 = (ImageView) findViewById(R.id.mainicon_3);
		mainicon_4 = (ImageView) findViewById(R.id.mainicon_4);
		mainicon_5 = (ImageView) findViewById(R.id.mainicon_5);
		mainIconDes_tv = (TextView) findViewById(R.id.mainIconDes_tv);
		signIn_tv = (TextView) findViewById(R.id.signIn_tv);
		btn_getChatting = (Button) findViewById(R.id.btn_getChatting);
	}

	/**
	 * init Datas
	 */
	private void initDatas() {
		ServiceUtil.startService(this);
		palyTalkContext		= this;
		pagePointViewList   = new ArrayList<ImageView>();
		addPagePoint();
		timerStart();
		createDir();
//		getWindowMana();
		ApplicationTrans appState = (ApplicationTrans) getApplicationContext();
		tpAuth = appState.getTpAuth();
	}

	private void createDir(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				getWindowMana();
				FileDir.create();
			}
		}).start();
	}

	
//	private void showToast(String str) {
//		Toast.makeText(PlayTalkActivity.this, str, Toast.LENGTH_SHORT).show();
//	}

	public void getWindowMana() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		Globals.width = dm.widthPixels;
		Globals.height = dm.heightPixels;
		Globals.density = dm.density;
	}

	/**
	 * All Button click event
	 */
	private void clickEvents() {
		btn_getChatting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Intent intent = new Intent(PlayTalkActivity.this,
				// ChatConversationActivity.class);
				// startActivity(intent);
				if(!networkIsAvailable(getApplicationContext())){
					new AlertDialog.Builder(PlayTalkActivity.this).setTitle(getResources().getString(R.string.main_networkerr_title)).setMessage(getResources().getString(R.string.main_networkerr_des)).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//进入无线网络配置界面
						}
					}).show();
					return;
				}
				
				if(Globals.skyid==0&&UserInfo.getImsi().substring(0, 3).equals("999")){//no imsi
					startActivity(new Intent(PlayTalkActivity.this, SignUpActivity.class));
					return;
				}
				progressDialog = ProgressDialog.show(PlayTalkActivity.this, getString(R.string.loading), getString(R.string.waittng), true, false); 
				progressDialog.show();
				PlayTalkUtil.login((ApplicationTrans) getApplicationContext(), Globals.skyid, new DataCallBack() {

					@Override
					public void Callback(int result, RspData resultdata, Object obj) {
						Message msg = new Message(); 
						msg.what = result; 
						msg.obj = resultdata;
						if (PlayTalkUtil.PLAYTALK_LOGIN_OK == result) {
							msg.obj = obj;
							LogManager.LogShow("PlayTalkActivity", "PLAYTALK_LOGIN_OK Globals.skyid = " + Globals.skyid);
						} else if (PlayTalkUtil.PLAYTALK_LOGIN_ERR == result) {
							LogManager.LogShow("PlayTalkActivity", "PLAYTALK_LOGIN_ERR");
						} else if (PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT == result) {
							LogManager.LogShow("PlayTalkActivity", "PLAYTALK_LOGIN_TIMEOUT");
						} else if (PlayTalkUtil.PLAYTALK_LOGIN_WAITING == result) {
							msg.obj = obj;
							LogManager.LogShow("PlayTalkActivity", "PLAYTALK_LOGIN_WAITING");
						}
						handler.sendMessage(msg);
					}
				});
			}
		});

		signIn_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				// test code start
				if (false) {// ���������ҽ���
					Intent intent = new Intent(PlayTalkActivity.this, CommunityActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {// ���ý���
					Intent intent = new Intent(PlayTalkActivity.this, SettingActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {// ���ý���
					Intent intent = new Intent(PlayTalkActivity.this, SettingPrivacyControlActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {// autotext ����
					Intent intent = new Intent(PlayTalkActivity.this, SettingAutoTextActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {// buddyinfo ����
					Intent intent = new Intent(PlayTalkActivity.this, BuddyInfoActivity.class);
					startActivity(intent);
					return;
				}
				if (false ) {// storesetting ����
					Intent intent = new Intent(PlayTalkActivity.this, SettingStoreSettingActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {// textinfo ����
					Intent intent = new Intent(PlayTalkActivity.this, TextInfoActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("title", "title");
					bundle.putString("info", "info");
					intent.putExtras(bundle);
					startActivity(intent);
					return;
				}
				if (false) {//
					Intent intent = new Intent(PlayTalkActivity.this, SignUpSetQuestionActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {//
					Intent intent = new Intent(PlayTalkActivity.this, DiscoverActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {//
					Intent intent = new Intent(PlayTalkActivity.this, FriendsMapActivity.class);
					startActivity(intent);
					return;
				}
				if (false) {//
					Intent intent = new Intent(PlayTalkActivity.this, HomeActivity.class);
					startActivity(intent);
					return;
				}
				if(false)
				{
					AlertDialog show = new AlertDialog.Builder(PlayTalkActivity.this)
							.setTitle("单选框").setIcon(android.R.drawable.ic_dialog_info)
						    .setSingleChoiceItems(
							     new String[] { "Item1", "Item2" }, 
							     0,
							     new DialogInterface.OnClickListener() {
							      public void onClick(DialogInterface dialog, int which) {
							    	  dialog.dismiss();
							      }
							     })
						     .setPositiveButton("OK", new DialogInterface.OnClickListener() {
						            public void onClick(DialogInterface dialog, int whichButton) {
						            	dialog.dismiss();
						            }
						        })
						     .show();
					return;
				}
				if(false){
					Calendar cal=Calendar.getInstance(); //获取时间用的
					DatePickerDialog date=new DatePickerDialog(PlayTalkActivity.this,new DatePickerDialog.OnDateSetListener(){
				         
				         public void onDateSet(DatePicker view,int year,int month,int dat){
				          
				         }
				        },cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
					date.show();
					return;
				}
				if(false){
					PhbBackUp phb = new PhbBackUp(getApplicationContext());
					phb.updatePhb(getApplicationContext(), "test", "121212", "", null);
					return; 
				}
				// test code end
				if(!networkIsAvailable(getApplicationContext())){
					new AlertDialog.Builder(PlayTalkActivity.this).setTitle(getResources().getString(R.string.main_networkerr_title)).setMessage(getResources().getString(R.string.main_networkerr_des)).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//进入无线网络配置界面
						}
					}).show();
					return;
				}
				Intent intent = new Intent(PlayTalkActivity.this, SignInActivity.class);
				startActivity(intent);
			}
		});

	}

	private void testTpFile() {
		String filename = Globals.FILE_PATH_AUDIO + "IMG2.jpg";
		TpFile tpFile = new TpFile();
		tpFile.tp_file_upload(filename, TpFile.FILE_TRANS_TYPE_NORMAL, 10, 0, new DataCallBack() {

			@Override
			public void Callback(int result, RspData resultdata, Object obj) {
				// TODO Auto-generated method stub
				LogManager.LogShow("PlayTalkActivity", "tp_file_upload  Callback result= " + result);
				if (result == TpFile.FILE_SERVER_UP_PROGRESS) {

				}
			}
		});
	}


	private void timerStart() {
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				if (isFirstChange) {
					isFirstChange = false;
				} else {
					if (currentIndex == 4)
						currentIndex = 0;
					else
						currentIndex++;
				}
				handler.sendEmptyMessage(CHANGEDATA);
			}
		}, 0, DELAYTIME);
	}

	private void changeIconAndValue() {
		String[] tips = tpAuth.tp_auth_get_tips_data();
		switch (currentIndex) {
		case 0:
			mainIconDes_tv.setText(tips[currentIndex]);
			iconPoint_5.setVisibility(View.INVISIBLE);
			iconPoint_1.setVisibility(View.VISIBLE);
			mainicon_1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_contacts_icon_on));
			mainicon_5.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_5));
			break;
		case 1:
			mainIconDes_tv.setText(tips[currentIndex]);
			iconPoint_1.setVisibility(View.INVISIBLE);
			iconPoint_2.setVisibility(View.VISIBLE);
			mainicon_1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_contacts_icon));
			mainicon_2.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_22));
			break;
		case 2:
			mainIconDes_tv.setText(tips[currentIndex]);
			iconPoint_2.setVisibility(View.INVISIBLE);
			iconPoint_3.setVisibility(View.VISIBLE);
			mainicon_2.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_2));
			mainicon_3.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_33));

			break;
		case 3:
			mainIconDes_tv.setText(tips[currentIndex]);
			iconPoint_3.setVisibility(View.INVISIBLE);
			iconPoint_4.setVisibility(View.VISIBLE);
			mainicon_3.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_3));
			mainicon_4.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_44));

			break;
		case 4:
			mainIconDes_tv.setText(tips[currentIndex]);
			iconPoint_4.setVisibility(View.INVISIBLE);
			iconPoint_5.setVisibility(View.VISIBLE);
			mainicon_4.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_4));
			mainicon_5.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainicon_55));

			break;
		}
	}

	/**
	 * init page point
	 */
	private void addPagePoint() {
		// pagePointViewList.clear();
		// pageControlLayout.removeAllViews();
		for (int i = 0; i < totalCount; i++) {
			ImageView imageView = new ImageView(this);
			imageView.setPadding(10, 0, 10, 10);
			imageView.setScaleType(ScaleType.CENTER);
			setPointImageResource(imageView, i);
			pagePointViewList.add(imageView);
			pageControlLayout.addView(imageView);
		}
	}

	/**
	 * change page point
	 */
	private void changePointImageResource() {
		for (int i = 0; i < totalCount; i++) {
			setPointImageResource(pagePointViewList.get(i), i);
		}
	}

	private void setPointImageResource(ImageView imageView, int index) {
		if (index == currentIndex)
			imageView.setImageResource(R.drawable.pagepoint1);
		else
			imageView.setImageResource(R.drawable.pagepoint2);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
//		ServiceUtil.stopService(this);
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		super.onDestroy();
	}
	
	
	public static boolean networkIsAvailable(Context context) {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.v("error", e.toString());
		}
		return false;
	}
	
}
